package com.atguigu.crowd.filter;

import com.atguigu.crowd.constant.AccessPassResource;
import com.atguigu.crowd.constant.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 判断请求是否需要放行
 * information
 * Created by Administrator on 2020/4/2.
 */
@Component
public class CrowdAccessFilter extends ZuulFilter {


    @Override
    public String filterType() {
        //在目标微服务前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

        /*
      判断当前请求是否要过滤，
      要过滤：返回true，继续执行run（）方法
      不过滤：返回false，直接放行
       */
    @Override
    public boolean shouldFilter() {
        //1.获取requestContext对象，线程本地化传过来的ThreadLocal
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2.通过requestContext对象获取当前请求对象
        HttpServletRequest request = requestContext.getRequest();
        //3.根据请求获取servletPath
        String servletPath = request.getServletPath();
        //4.判断当前servletPath路劲是否在我们放行请求set集合中
        boolean result = AccessPassResource.PASS_RES_SET.contains(servletPath);
        //5.如果的到的结果为true，不需要拦截
        if (result){
            return  false;
        }
        //6.使用工具方法判断当前资源是否是静态资源,结果为true，则需要放行，返回false不做filter
        return !AccessPassResource.judgeCurrentServletPathWetherStaticResource(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取当前请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //2.获取当前Session对象
        HttpSession session = request.getSession();
        //3.需要从Session对象中获取已登入的用户
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        //4.判断loginMember是否为空
        if (loginMember==null){
            //5.从requestContext对象中获取response对象
            HttpServletResponse response = requestContext.getResponse();
            //6.将提示信息存入session域
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
            //7.重定向到auth-member工程中登录的页面
            try {
                //http://localhost
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
